//
//  LJEmoction.swift
//  LJ表情键盘
//
//  Created by Raymond on 15/12/28.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
/// 表情包模型
class LJEmoctionPackage: NSObject {
    /// 表情包文件夹名称
    var id: String?
    /// 表情包名称
    var group_name_cn: String?
    /// 表情数组
    var emoticons: [LJEmoction] = [LJEmoction]()
    /// 表情包所在路径
    static let bundlePath: String = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
    /// 所有的表情包模型
    static let packages = LJEmoctionPackage.loadPackages()
    
    /// 表情包构造函数
    init(id: String){
        self.id = id
        super.init()
    }
    
    /// 加载所有表情包方法
    private class func loadPackages() -> [LJEmoctionPackage]? {
        let plistPath = bundlePath + "/emoticons.plist"
//        print(plistPath)
        let dict = NSDictionary(contentsOfFile: plistPath)!
        
        if let array = dict["packages"] as? [[String : AnyObject]] {
            // 保存表情包得数组
            var packages = [LJEmoctionPackage]()
            
            // 创建最近表情包
            let currentPackage = LJEmoctionPackage(id: "")
            
            // 设置表情包名称
            currentPackage.group_name_cn = "最近"
            
            // 添加
            packages.append(currentPackage)
            
            // 添加空白格和删除按钮
            currentPackage.appendEmptyEmoction()
            
            for dict in array {
                let id = dict["id"] as! String
                let package = LJEmoctionPackage(id: id)
                // 加载表情包
                package.loadEmoction()
                packages.append(package)
            }
            return packages
        }
        return nil
    }
    /// 加载表情包方法
    func loadEmoction() {
        // 获取plist文件路径
        let plistPath = LJEmoctionPackage.bundlePath + "/\(id!)" + "/info.plist"
        let dict = NSDictionary(contentsOfFile: plistPath)!
        group_name_cn = dict["group_name_cn"] as? String
        if let array = dict["emoticons"] as? [[String : AnyObject]] {
            var index = 0
            for dict in array {
                // 根据字典创建表情模型
                let emoction = LJEmoction(id: id, dict: dict)
                // 添加数组属性
                emoticons.append(emoction)
                index++
                if index == 20 {
                    emoticons.append(LJEmoction(isRemoveEmoction: true))
                    // 清空index，从0开始
                    index = 0
                }
            }
        }
        // 添加空表情
        appendEmptyEmoction()
    }
    
    private func appendEmptyEmoction() {
        // 判断是否满21个
        let count = emoticons.count % 21
        
        if count > 0 || emoticons.count == 0 {
            for _ in count..<20 {
                emoticons.append(LJEmoction(isRemoveEmoction: false))
            }
            // 添加删除按钮
            emoticons.append(LJEmoction(isRemoveEmoction: true))
        }
    }
    
    // 添加表情模型到最近表情包
    class func addFavorateEmoction(emoction: LJEmoction) {
        // 空白按钮不需要添加
        if emoction.pngString == nil && emoction.emoji == nil {
            return
        }
        // 删除按钮不需要添加
        if emoction.isRemoveEmoction {
            return
        }
        // 添加表情使用次数
        emoction.times++
        // 获取最近表情包里得所有表情
        var recentEmoctions = packages![0].emoticons
        // 移除删除按钮，不参与排序
        let removeEmoction = recentEmoctions.removeLast()
        // 判断是否已存在该表情
        let isEsit = recentEmoctions.contains(emoction)
        if !isEsit {
            recentEmoctions.append(emoction)
        }
        // 重新排序
        recentEmoctions =  recentEmoctions.sort{ (e1, e2) -> Bool in
            e1.times > e2.times
        }
        // 如果有添加新元素需要删除最后一个
        if !isEsit {
            recentEmoctions.removeLast()
        }
        // 将删除按钮添加回来
        recentEmoctions.append(removeEmoction)
        // swfit 是值传递，需要将数组重新赋值回来
        packages![0].emoticons = recentEmoctions
    }
    
    // 打印对象调用方法
    override var description: String {
        return "\n\t表情包模型:id:\(id), group_name_cn: \(group_name_cn), emoticons: \(emoticons))"
    }
}
/// 表情模型
class LJEmoction: NSObject {
    /// 表情包文件夹名称
    var id: String?
    /// 表情名称
    var chs: String?
    /// 表情图片
    var png: String?{
        didSet{
            pngString = LJEmoctionPackage.bundlePath + "/\(id!)/\(png!)"
        }
    }
    /// emoji表情字符
    var code: String?{
        didSet{
            // 设置扫描器
            let scanner = NSScanner(string: code!)
            // 扫描
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
            let scalar = UnicodeScalar(result)
            
            let c = Character(scalar)
            emoji = String(c)
            
        }
    }
    
    /// 表情图片路径
    var pngString: String?
    
    /// emoji表情
    var emoji: String?
    
    /// 删除按钮标志
    var isRemoveEmoction: Bool = false
    
    /// 使用次数
    var times = 0
    
    // 构造方法
    init(id: String?, dict: [String : AnyObject]){
        super.init()
        self.id = id
        // kvc
        setValuesForKeysWithDictionary(dict)
    }
    
    init(isRemoveEmoction: Bool) {
        super.init()
        self.isRemoveEmoction = isRemoveEmoction
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 对象打印方法
    override var description: String {
        return "\n\t\t表情模型:chs: \(chs), png: \(png), code: \(code)"
    }
    
}
